#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/5/26 16:19
# @Author : wn 
# @File: customerrulerel.py
# @SoftWare: PyCharm
# @Site:
# @Table:
# ｡◕‿◕｡｡◕‿◕｡｡◕‿◕｡


from django.shortcuts import render, HttpResponse, redirect
from Manager.models import *
from Rbac.models import *
from Manager.views.service import my_page
from django.http import JsonResponse
import json
from Django_Admin.enumType import *

from Rbac.utils.login_deco import *

@auth
def customerrulerel_list(request):
    # 当前在第几页
    off = request.GET.get('offset', None)
    # 一页几条数据
    lim = request.GET.get('limit', None)
    # 获取url后拼接的search
    search = request.GET.get('search', None)
    # t_customer实例，t_rule实例
    customers = Customer.objects.all()
    rules = Rule.objects.all()

    # 判断url后面是否拼接了search，没有，返回页面；有显示搜索条件的值
    if search is None:
        return render(request, 'customerrulerel.html', {"customers": customers, "rules": rules})
    else:
        # 按搜索条件获取值
        if search:
            # 如果多个主键，这filter中，连写另一个值可以吗
            crr_list = Customerrulerel.objects.values().filter(customerid__contains=search)
        else:
            crr_list = Customerrulerel.objects.values()
        # 把queryset转成列表[{},{}]
        crr_list = list(crr_list)
        for item in crr_list:
            # 联合主键，用id
            item['option'] = item['id']
            # 枚举值
        result = my_page(crr_list, lim, off)
        return JsonResponse(result, safe=False)


# 添加，修改，删除
def customerrulerel_modify(request):
    ##拿到登录用户id
    userid = request.session["id"]
    isdelete = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='customerrulerel_list(delete)')
    ismodify = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='customerrulerel_list(modify)')
    isadd = Customer.objects.filter(customerid=userid).filter(
        roles__permissions__url__endswith='customerrulerel_list(add)')
    if request.method == 'GET':
        # 联合主键，id
        crr_id = request.GET['id']
        item = Customerrulerel.objects.values().filter(id=crr_id).first()
        # print('被修改的值：', item)
        if item:
            return JsonResponse(item, safe=False)
    else:
        if request.POST.get('delete', None):
            if isdelete:
                # 删除
                crrid = request.POST.get('id')
                Customerrulerel.objects.filter(id=crrid).delete()
                return HttpResponse('y')
            else:
                return HttpResponse("该用户无操作权限！")
        else:
            try:
                data = request.POST
                # print(json.loads(data['id']))
                if Customerrulerel.objects.filter(customerid=json.loads(data["customerid"])[0], ruleid=json.loads(data["ruleid"])[0]):
                    return HttpResponse("当前记录已存在！")
                if json.loads((data['id']))[0]:
                    if Customerrulerel.objects.filter(id=json.loads(data['id'])[0]).count() >= 1:
                        # 修改
                        if ismodify:
                            # 实例
                            Customerrulerel.objects.filter(id=json.loads(data['id'])[0]).update(
                                customerid=json.loads(data["customerid"])[0],
                                ruleid=int(json.loads(data["ruleid"])[0]),
                            )
                            return HttpResponse("y")
                        else:
                            return HttpResponse("该用户无操作权限！")
                else:
                    if isadd:
                        # 新增
                        Customerrulerel.objects.create(
                            customerid=json.loads(data["customerid"])[0],
                            ruleid=int(json.loads(data["ruleid"])[0]),
                        )
                        return HttpResponse('y')
                    else:
                        return HttpResponse("该用户无操作权限！")
            except Exception as e:
                return HttpResponse(e)
    return render(request, 'customerrulerel.html')